package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"me/123/common/proto/user"
)

type UserHandler func(ctx context.Context, in user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler UserHandler) (interface{}, error) {
	conn, err := grpc.Dial("127.0.0.1:8081", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
		return nil, err
	}
	defer conn.Close()
	client := user.NewUserClient(conn)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	return res, err
}

func Login(ctx context.Context, req *user.LoginRequest) (*user.LoginResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.Login(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, err
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.LoginResponse), err
}

func CollectVoucher(ctx context.Context, req *user.CollectVoucherRequest) (*user.CollectVoucherResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.CollectVoucher(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, err
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.CollectVoucherResponse), err
}
